package com.shsxt.crm.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageInfo;
import com.shsxt.common.util.Md5Util;
import com.shsxt.common.util.Result;
import com.shsxt.crm.dao.YgRoleDao;
import com.shsxt.crm.dao.YgUserDao;
import com.shsxt.crm.dao.YgUserRoleDao;
import com.shsxt.crm.model.YgRole;
import com.shsxt.crm.model.YgUser;
import com.shsxt.crm.model.YgUserRole;
import com.shsxt.crm.service.ISystemUserService;
import com.shsxt.crm.service.IUserService;
import com.shsxt.framework.exception.YgException;

@Service
public class SystemUserServiceImpl implements ISystemUserService {

	@Autowired
	private IUserService userService;

	@Autowired
	private YgUserDao userDao;

	@Autowired
	private YgUserRoleDao userRoleDao;

	@Override
	public Map<String, Object> queryUsersByParams(YgUser ygUser) {

		PageInfo<YgUser> pageInfo = userService.querySysUser(ygUser);

		List<YgUser> list = pageInfo.getList();

		Map<String, Object> map = new HashMap<>();
		map.put("total", pageInfo.getTotal());
		map.put("rows", pageInfo.getList());
		return map;
	}

	@Override
	@Transactional
	public Result insertSystemUser(YgUser ygUser) {

		Map<String, Object> params = new HashMap<>();
		params.put("userName", ygUser.getUserName());
		params.put("isValid", 1);
		YgUser one = userDao.findOne(params);
		if (one != null) {// 已经存在
			throw new YgException("500", "用户名称重复");
		}

		ygUser.setCreateDate(new Date());
		ygUser.setUpdateDate(new Date());
		ygUser.setUserPwd(Md5Util.encode(ygUser.getUserPwd()));
		long ste = userDao.saveSte(ygUser);// 用户基本信息
		if (ste != 1) {
			throw new YgException("500", "添加用户失败");
		}
		// 再次查询获取用户信息
		one = userDao.findOne(params);
		// 保存用户角色
		YgUserRole userRole = new YgUserRole();
		userRole.setUserId(one.getId());
		userRole.setRoleId(ygUser.getRoleIds());
		userRole.setCreateDate(new Date());
		userRole.setUpdateDate(new Date());
		long saveSte = userRoleDao.saveSte(userRole);
		if (saveSte != 1) {
			throw new YgException("500", "添加用户角色绑定失败");
		}
		return Result.success("添加用户成功");
	}

	@Override
	@Transactional
	public Result delSystemUser(Integer[] ids) {
		for (Integer id : ids) {
			YgUser ygUser = new YgUser();
			ygUser.setId(id);
			ygUser.setIsValid(0);
			long ste = userDao.updateSte(ygUser);
			int uid = userRoleDao.delUserRoleByUid(id);
			if (ste != 1 || uid != 1) {
				throw new YgException("500", "删除失败");
			}
		}
		return Result.success("删除成功");
	}
}
